const express = require('express')
const path = require('path')
const cors = require('cors')
const { paginateResults } = require('./utils/utils')
const admin = require('firebase-admin')

const serviceAccount = require('./sber-reactjs-firebase-adminsdk-ta0he-15d34e478e.json')

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: 'https://sber-reactjs-default-rtdb.firebaseio.com',
})

const db = admin.database()
const app = express()
const PORT = process.env.PORT || 5002

app.use(cors())
app.use(express.json())

app.use(express.static(path.join(__dirname, 'my-blog/build')))

// Получить все посты с пагинацией
app.get('/posts', (req, res) => {
  const page = parseInt(req.query.page) || 1
  const limit = parseInt(req.query.limit) || 10

  db.ref('posts').once(
    'value',
    (snapshot) => {
      const posts = snapshot.val()
      const paginatedResults = paginateResults(posts, page, limit)
      res.json(paginatedResults)
    },
    (errorObject) => {
      console.error('The read failed: ' + errorObject.code)
      res.status(500).send('Error reading data from Firebase')
    }
  )
})

// Получить результаты поиска с пагинацией
app.get('/posts/search', (req, res) => {
  const filterSelect = req.query.filter
  const searchTerm = req.query.term.toLowerCase()
  const page = parseInt(req.query.page) || 1
  const limit = parseInt(req.query.limit) || 10

  const postsRef = db.ref('posts')
  postsRef.once(
    'value',
    (snapshot) => {
      const posts = snapshot.val()
      const searchResults = Object.values(posts).filter((post) => post[filterSelect].toLowerCase().includes(searchTerm))
      const paginatedResults = paginateResults(searchResults, page, limit)
      res.json(paginatedResults)
    },
    (errorObject) => {
      console.error('The read failed: ' + errorObject.code)
      res.status(500).send('Error reading data from Firebase')
    }
  )
})

// Получить один пост по ID
app.get('/posts/:id', (req, res) => {
  const postId = parseInt(req.params.id)
  const postsRef = db.ref('posts')

  postsRef.once(
    'value',
    (snapshot) => {
      const posts = snapshot.val()
      const post = posts.find((post) => post.id === postId)
      if (!post) {
        res.status(404).send('Пост не найден')
        return
      }
      res.json(post)
    },
    (errorObject) => {
      console.error('The read failed: ' + errorObject.code)
      res.status(500).send('Error reading data from Firebase')
    }
  )
})

// Создать новый пост
app.post('/posts', (req, res) => {
  const newPost = {
    userID: req.body.userID,
    title: req.body.title,
    body: req.body.body,
    url: req.body.url,
  }
  const postsRef = db.ref('posts')
  postsRef.once('value', (snapshot) => {
    const posts = Object.values(snapshot.val())
    const postsLength = posts.length
    const lastPostId = posts[postsLength - 1].id
    newPost.id = lastPostId + 1
    const newPosts = [...posts, newPost]
    db.ref('posts')
      .set(newPosts)
      .then(() => {
        res.json(newPosts)
      })
      .catch((error) => {
        console.error('Error updating posts in Firebase: ', error)
        res.status(500).send('Ошибка сервера')
      })
  })
})

// Обновить существующий пост
app.put('/posts/:id', (req, res) => {
  const postId = req.params.id
  const updatedPost = {
    title: req.body.title,
    body: req.body.body,
  }
  const postRef = db.ref(`posts/${postId}`)
  postRef
    .update(updatedPost)
    .then(() => {
      res.json({ id: postId, ...updatedPost })
    })
    .catch((error) => {
      console.error('Error updating data to Firebase: ', error)
      res.status(500).send('Ошибка сервера')
    })
})

// Удалить пост
app.delete('/posts/:id', (req, res) => {
  const postId = req.params.id

  // Получаем все посты
  const postsRef = db.ref('posts')

  let postIndex = 0
  postsRef.once('value', (snapshot) => {
    const posts = snapshot.val()
    postIndex = posts.find((post, i) => {
      if (post.id === postId) {
        return i
      }
    })
  })

  const postRef = db.ref(`posts/${postIndex}`)
  postRef
    .remove()
    .then(() => {
      db.ref('posts').once(
        'value',
        (snapshot) => {
          const posts = snapshot.val() || {}
          const updatedPosts = Object.values(posts)
          const newPosts = updatedPosts.filter((post) => post.id !== postId)
          db.ref('posts')
            .set(newPosts)
            .then(() => {
              res.json(newPosts)
            })
            .catch((error) => {
              console.error('Error updating posts in Firebase: ', error)
              res.status(500).send('Ошибка сервера')
            })
        },
        (errorObject) => {
          console.error('The read failed: ' + errorObject.code)
          res.status(500).send('Ошибка сервера')
        }
      )
    })
    .catch((error) => {
      console.error('Error deleting data from Firebase: ', error)
      res.status(500).send('Ошибка сервера')
    })
})
// Получить комментарии для конкретного поста
// app.get('/posts/:postId/comments', (req, res) => {
//   const postId = parseInt(req.params.postId)

//   const postComments = comments.filter((comment) => comment.postId === postId)

//   res.json(postComments)
// })

app.listen(PORT, () => {
  console.log(`Сервер запущен на порту ${PORT}`)
})
